<template>
  <div>
    <a-cascader
      :options="options"
      :load-data="loadData"
      change-on-select
      allowClear
      placeholder="请选择区域"
      @change="onchange"
    />
  </div>
</template>
<script>
import { getAreaList, getCityList } from "@/api/system/sysArea";
export default {
  props: {
    value: {
      type: Array,
    },
  },
  created() {
    this.change();
  },
  data() {
    return {
      arr: this.value,
      // 级联父节点
      options: [],
      // 区域对象
      area: {
        level: 99,
        code: "42",
      },
    };
  },
  methods: {
    onchange(e, value) {
      this.value = e;
    },
    // 判断是回显还是新增
    change() {
      if (this.value == null) {
        this.AreaList();
      } else {
        this.updateaAreaList();
      }
    },
    AreaList() {
      getAreaList(this.area).then((res) => {
        res.data.map((v) => {
          var object = {
            value: v.value,
            label: v.label,
            isLeaf: false,
            code: v.code,
            level: 2,
          };
          this.options.push(object);
        });
      });
    },
    // 加载子项
    loadData(selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      this.area.code = targetOption.code;
      this.area.level = 2;
      targetOption.loading = true;
      setTimeout(() => {
        targetOption.loading = false;
        getCityList(this.area).then((res) => {
          targetOption.children = res.data;
          this.options = [...this.options];
        });
      }, 300);
    },
    // 回显数据
    updateaAreaList() {
      getAreaList(this.area).then((res) => {
        res.data.map((v) => {
          var object = {
            value: v.value,
            label: v.label,
            isLeaf: false,
            children: undefined,
            code: v.code,
          };

          if (v.name === this.arr[0]) {
            this.area.code = v.code;
            this.area.level = 2;
            getCityList(this.area).then((res) => {
              object.children = res.data;
            });
          }

          this.options.push(object);
        });
      });
    },
  },
};
</script>
